import React, { memo, useEffect, useRef, useState } from 'react'
import { HeaderWrapper } from './style'
import HeaderLeft from './c-cpns/header-left'
import HeaderCenter from './c-cpns/header-center'
import HeaderRight from './c-cpns/header-right'
import { useSelector } from 'react-redux'
import classNames from 'classnames'
import usePosition from '@/hooks/usePostion'
import { ThemeProvider } from 'styled-components'

const AppHeader = memo(() => {
  /** 定义组件内部的状态 */
  const [isSearch, setIsSearch] = useState(false)

  const { headerConfig } = useSelector(state=>({
    headerConfig: state.main.headerConfig
  }))
  const { isFixed, topAlpha } = headerConfig


  const prevY = useRef(0)

  const { scrollY } = usePosition()
  // 在正常情况的情况下(搜索框没有弹出来), 不断记录值
  if (!isSearch) prevY.current = scrollY
  // 在弹出搜索功能的情况, 滚动的距离大于之前记录的距离的30(相减取绝对值)
  if (isSearch && Math.abs(scrollY - prevY.current) > 30) setIsSearch(false)
  const isTop = topAlpha && scrollY === 0
console.log(isTop)
  /** 透明度的逻辑 */
  // function setSearchHandler(isSearch){
  //   setIsSearch(isSearch)
  // }
  return (

    <ThemeProvider theme={{ isTop }}>
    <HeaderWrapper className={classNames({ fixed: isFixed||isSearch })} isTopSearch={isSearch || isTop}>
        <div className="content">
          <div className="top">
            <HeaderLeft />
            <HeaderCenter isSearch={isSearch||isTop} setSearchHandler={setIsSearch} />
            <HeaderRight />
          </div>
          <div className="bottom"></div>
        </div>
        {isSearch && <div className="cover" onClick={e=>setIsSearch(false)}></div>}
    </HeaderWrapper>
    </ThemeProvider>
  )
})

export default AppHeader